package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"red-book-manage/cache"
	"red-book-manage/model"
	"strconv"
	"time"
)

func Add(c *gin.Context) {
	Title := c.PostForm("Title")
	Content := c.PostForm("Content")
	Author := c.PostForm("Author")
	if Title == "" || Content == "" || Author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	data := model.Article{
		Title:   Title,
		Content: Content,
		Author:  Author,
	}
	err := model.DB.Debug().Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	var article model.Article
	model.DB.Debug().Where("id=?", data.ID).First(&article)
	redis_key := "add_article" + strconv.Itoa(int(data.ID))
	jsonData, _ := json.Marshal(article)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func Detail(c *gin.Context) {
	id := c.Query("id")
	var article model.Article
	err := model.DB.Debug().Where("id=?", id).First(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "展示失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": article,
	})
	return
}

func Del(c *gin.Context) {
	id := c.PostForm("id")
	var article model.Article
	err := model.DB.Debug().Where("id=?", id).Delete(&article).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "del_article"
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
	return
}

func List(c *gin.Context) {
	redis_key := "list_article"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	var article []model.Article
	if cacheData == "" {
		model.DB.Debug().Find(&article)
		jsonData, _ := json.Marshal(article)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &article)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "展示成功",
		"data": article,
	})
	return
}
